/**
******************************************************************************
* @file    		W5500.c
* @author  		WIZnet Software Team 
* @version 		V1.0
* @date    		2015-02-14
* @brief   		读写W5500寄存器底层函数
******************************************************************************
*/
#include "W5500_Driver.h"
#include "eeprom.h"
#include "dhcp.h"
//#include "socket.h"
//#ifdef __DEF_IINCHIP_PPP__
//#include "md5.h"
//#endif

#pragma region //===========字段==========
static const char *TAG = "W5500";
/*定义MAC地址,如果多块W5500网络适配板在同一现场工作，请使用不同的MAC地址*/
uint8_t mac[6] = DEFINE_MAC;
/*定义默认IP信息*/
uint8_t subnet[4] = DEFINE_SUB_NET; /*定义W5500默认子网掩码*/
uint8_t gateway[4] = DEFINE_GATEWAY; /*定义W5500默认网关*/
uint8_t dns_server[4] = DEFINE_DNS; /*定义W5500默认DNS*/


uint16_t SSIZE[MAX_SOCK_NUM] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // Max Tx buffer
uint16_t RSIZE[MAX_SOCK_NUM] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // Max Rx buffer
sSPI_DRIVER *pW5500;
CONFIG_MSG  ConfigMsg = { .sw_ver = FW_VER }; /*配置结构体*/
#pragma endregion

#pragma region //===========公共变量==========
uint8_t txsize[MAX_SOCK_NUM] = { 2, 2, 2, 2, 2, 2, 2, 2 }; //tx buffer set	K bits
uint8_t rxsize[MAX_SOCK_NUM] = { 2, 2, 2, 2, 2, 2, 2, 2 }; //rx buffet set  K bits

uint8_t local_ip[4] = DEFINE_LOCAL_IP; /*定义W5500默认IP地址*/
uint16_t local_port = DEFINE_LOCAL_PORT; /*定义本地端口*/
/*定义远端IP信息*/
uint8_t  remote_ip[4] = DEFINE_REMOTE_IP; /*定义远端IP地址*/
uint16_t remote_port = DEFINE_REMOTE_PORT; /*定义远端端口号*/

/*IP配置方法选择，请自行选择*/
uint8_t	ip_from = IP_FROM_MODE;				
EEPROM_MSG_STR EEPROM_MSG; /*EEPROM存储信息结构体*/

volatile uint8_t	    ntptimer  = 0; /*NPT秒计数*/
#pragma endregion

#pragma region //===========私有函数=============
/**
*@brief		写入一个8位数据到W5500
*@param		addrbsb: 写入数据的地址
*@param   data：写入的8位数据
*@return	无
*/
void IINCHIP_WRITE(uint32_t addrbsb, uint8_t data)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_AddrCtrlByte_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 1;
	buf.BData = data;
	SPI_Only_Tx(pW5500, buf.Byte, sizeof(W5500_AddrCtrlByte_t));
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
}
/**
*@brief		从W5500读出一个8位数据
*@param		addrbsb: 写入数据的地址
*@param   data：从写入的地址处读取到的8位数据
*@return	无
*/
uint8_t IINCHIP_READ(uint32_t addrbsb)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_AddrCtrlByte_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 0;
	buf.BData = 0;
	SPI_Tx_Rx(pW5500, buf.Byte, buf.Byte, sizeof(W5500_AddrCtrlByte_t));
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
	return buf.BData;    
}
/*
********************************************************************************
** 描述: 向W5500的addrbsb写入16bit数据.addrbsb低8位为控制段,addrbsb的8位以上为地址段.
********************************************************************************/
void W5500_WriteWord(uint32_t addrbsb, uint16_t data)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_AddrCtrlWord_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 1;
	buf.WData = __REV16(data);
	SPI_Only_Tx(pW5500, buf.Byte, sizeof(W5500_AddrCtrlWord_t));
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
}
uint16_t W5500_ReadWord(uint32_t addrbsb)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_AddrCtrlWord_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 0;
	buf.WData = 0;
	SPI_Tx_Rx(pW5500, buf.Byte, buf.Byte, sizeof(W5500_AddrCtrlWord_t));
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
	return __REV16(buf.WData);    
}
/**
*@brief		向W5500写入len字节数据
*@param		addrbsb: 写入数据的地址
*@param   buf：写入字符串
*@param   len：字符串长度
*@return	len：返回字符串长度
*/
uint16_t wiz_write_buf(uint32_t addrbsb, uint8_t* pCh, uint16_t len)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_Addr_Ctrl_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 1;
	SPI_Only_Tx(pW5500, buf.Byte, 3);
	SPI_Only_Tx(pW5500, pCh, len);
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
	return len;  
}
/**
*@brief		从W5500读出len字节数据
*@param		addrbsb: 读取数据的地址
*@param 	buf：存放读取数据
*@param		len：字符串长度
*@return	len：返回字符串长度
*/
uint16_t wiz_read_buf(uint32_t addrbsb, uint8_t* pRx_buf, uint16_t len)
{
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_RESET);
	W5500_Addr_Ctrl_t buf;
	buf.RegAddr = __REV16(addrbsb >> 8);
	buf.Byte[2] = addrbsb;
	buf.RWB = 0;
	SPI_Only_Tx(pW5500, buf.Byte, 3);
	SPI_Only_Rx(pW5500, pRx_buf, len);
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);                           
	return len;
}
#pragma endregion

#pragma region //===========方法API===============
/*
********************************************************************************
** 描述: 初始化W5500使用的SPI口,复位W5500,配置MAC地址,配置IP地址,初始化8个Socket的发送接收缓存大小.
** 返回: 0,1：成功，其它：失败
********************************************************************************/
int W5500_Init(SPI_HandleTypeDef *hspi/*[I]指向SPI句柄*/, osSemaphoreId done_sem/*[I]SPI通讯完成信号量句柄*/)
{
	int ret = 0;
	ret = SPI_Init(&pW5500, hspi, done_sem);
	if (ret < 0)
	{
		PRINT("W5500初始化SPI失败! 故障码=%d \r\n", ret);
		return ret;
	}
	
	HAL_GPIO_WritePin(W5500_nCS_GPIO_Port, W5500_nCS_Pin, GPIO_PIN_SET);
	reset_w5500(); /*硬复位W5500*/
	if ((ret = IINCHIP_READ(VERSIONR)) != 0x04)
	{
		PRINT("Read VERSIONR err:%d\r\n", ret);
		if ((ret = IINCHIP_READ(VERSIONR)) != 0x04)
		{
			PRINT("ReRead VERSIONR err:%d\r\n", ret);
			return -1;
		}
	}
	set_w5500_mac(); /*配置MAC地址*/
	socket_buf_init(txsize, rxsize); /*初始化8个Socket的发送接收缓存大小*/
	return 0;
}

/**
*@brief		W5500复位设置函数
*@param		无
*@return	无
*/
void reset_w5500(void)
{
	HAL_GPIO_WritePin(W5500_nRST_GPIO_Port, W5500_nRST_Pin, GPIO_PIN_RESET);
	osDelay(2);	//低电平复位W5500至少保持500us以上
	HAL_GPIO_WritePin(W5500_nRST_GPIO_Port, W5500_nRST_Pin, GPIO_PIN_SET);
	osDelay(200);	//保持高电平1ms复位完成
}
/**
*@brief		配置W5500的MAC地址
*@param		无
*@return	无
*/
void set_w5500_mac(void)
{
	memcpy(ConfigMsg.mac, mac, 6);
	setSHAR(ConfigMsg.mac); /*配置MAC*/
	memcpy(DHCP_GET.mac, mac, 6);
}
__weak int LoadEEPROM_Var(void)
{
	memcpy(EEPROM_MSG.mac, mac, 6);
	memcpy(EEPROM_MSG.lip, local_ip, 4);
	memcpy(EEPROM_MSG.sub, subnet, 4);
	memcpy(EEPROM_MSG.gw, gateway, 4);
	
	int ret = EE_Init();
	if (ret == EE_OK)
	{
		ret = EE_LoadAllVar((uint16_t*)&EEPROM_MSG);
		if (ret != EE_OK)
		{
			EE_SaveAllVar((uint16_t*)&EEPROM_MSG); /*使用全部或部分的默认信息，存储到EEPROM中*/
		}
	}
	return ret;
}
/**
*@brief		配置W5500的IP地址
*@param		无
*@return	无
*/
void set_w5500_ip(void)
{	
	/*复制默认定义的配置信息到配置结构体*/
	memcpy(ConfigMsg.mac, mac, 6);
	memcpy(ConfigMsg.lip, local_ip, 4);
	memcpy(ConfigMsg.sub, subnet, 4);
	memcpy(ConfigMsg.gw, gateway, 4);
	memcpy(ConfigMsg.dns, dns_server, 4);
	
	int ret = LoadEEPROM_Var();
	/*使用EEPROM存储的IP参数*/	
	if (ip_from == IP_FROM_EEPROM)
	{
		/*如果读取EEPROM中MAC信息,如果已配置，则可使用*/		
		if (ret == EE_OK && *(EEPROM_MSG.mac) == 0x00 && *(EEPROM_MSG.mac + 1) == 0x08 && *(EEPROM_MSG.mac + 2) == 0xdc)		
		{
			PRINT("%s: IP from EEPROM\r\n", TAG);
			/*复制EEPROM配置信息到配置的结构体变量*/
			memcpy(ConfigMsg.mac, EEPROM_MSG.mac, 6);
			memcpy(ConfigMsg.lip, EEPROM_MSG.lip, 4);				
			memcpy(ConfigMsg.sub, EEPROM_MSG.sub, 4);
			memcpy(ConfigMsg.gw, EEPROM_MSG.gw, 4);
		}
		else
		{
			PRINT("%s: 使用定义的IP信息配置W5500\r\n", TAG);
		}
	}

	/*使用DHCP获取IP参数，需调用DHCP子函数*/		
	if (ip_from == IP_FROM_DHCP)								
	{
		/*复制DHCP获取的配置信息到配置结构体*/
		if (dhcp_ok == 1)
		{
			PRINT("%s: IP from DHCP\r\n", TAG);		 
			memcpy(ConfigMsg.lip, DHCP_GET.lip, 4);
			memcpy(ConfigMsg.sub, DHCP_GET.sub, 4);
			memcpy(ConfigMsg.gw, DHCP_GET.gw, 4);
			memcpy(ConfigMsg.dns, DHCP_GET.dns, 4);
		}
		else
		{
			PRINT("%s:DHCP子程序未运行,或者不成功\r\n", TAG);
			PRINT("使用定义的IP信息配置W5500\r\n");
		}
	}
		
	/*将IP配置信息写入W5500相应寄存器*/	
	setSUBR(ConfigMsg.sub);
	setGAR(ConfigMsg.gw);
	setSIPR(ConfigMsg.lip);
	
	getSIPR(local_ip);		
	getSUBR(subnet);
	getGAR(gateway);
	PRINT("%s IP地址   : %d.%d.%d.%d\r\n", TAG, local_ip[0], local_ip[1], local_ip[2], local_ip[3]);
	PRINT("%s 子网掩码 : %d.%d.%d.%d\r\n", TAG, subnet[0], subnet[1], subnet[2], subnet[3]);
	PRINT("%s 网关     : %d.%d.%d.%d\r\n", TAG, gateway[0], gateway[1], gateway[2], gateway[3]);
}

/*
********************************************************************************
**描述: 软复位W5500  reset iinchip
*******************************************************************************/
void iinchip_init(void)
{
	setMR(MR_RST);
	PRINT("MR value is %02x \r\n", IINCHIP_READ(MR));
}

/**
*@brief		This function is to get the Max size to receive.
*@param		s: socket number
*@return	This function return the RX buffer size has been setted
*/
uint16_t getIINCHIP_RxMAX(uint8_t s)
{
	return RSIZE[s];
}	

/**
*@brief		This function is to get the Max size to receive.
*@param		s: socket number
*@return	This function return the RX buffer size has been setted
*/
uint16_t getIINCHIP_TxMAX(uint8_t s)
{
	return SSIZE[s];
}

/**
*@brief		This function is to set up gateway IP address.
*@param		addr: a pointer to a 4 -byte array responsible to set the Gateway IP address 
*@return	None
*/
void setGAR(uint8_t * addr )
{
    wiz_write_buf(GAR0, addr, 4);
}

/**
*@brief		This function is to get gateway IP address.
*@param		addr: a pointer to a 4 -byte array responsible to get the Gateway IP address  
*@return	None
*/
void getGAR(uint8_t * addr)
{
    wiz_read_buf(GAR0, addr, 4);
}

/**
*@brief 	This function is to set up SubnetMask address
*@param		addr: a pointer to a 4 -byte array responsible to set the subway IP address.  
*@return	None
*/
void setSUBR(uint8_t * addr)
{   
    wiz_write_buf(SUBR0, addr, 4);
}
/**
*@brief		This function is to set up MAC address.
*@param		addr: a pointer to a 6 -byte array responsible to set the MAC address.  
*@return	None
*/
void setSHAR(uint8_t * addr)
{
	wiz_write_buf(SHAR0, addr, 6);  
}

/**
*@brief		This function is to set up Source IP address.
*@param		addr:a pointer to a 4 -byte array responsible to set the Source IP addres.  
*@return	None
*/
void setSIPR(uint8_t * addr)
{
    wiz_write_buf(SIPR0, addr, 4);  
}

/**
*@brief		This function is to get Subnet mask.
*@param		addr:a pointer to a 4 -byte array responsible to set the Subnet mask.  
*@return	None
*/
void getSUBR(uint8_t * addr)
{
    wiz_read_buf(SUBR0, addr, 4);
}

/**
*@brief		This function is to get up Source MAC .
*@param		addr: a pointer to a 6 -byte array responsible to get the MAC  
*@return	None
*/
void getSHAR(uint8_t * addr)
{
    wiz_read_buf(SHAR0, addr, 6);
}

/**
*@brief		This function is to get up Source IP .
*@param		addr: a pointer to a 4 -byte array responsible to get the Source IP  
*@return	None
*/
void getSIPR(uint8_t * addr)
{
    wiz_read_buf(SIPR0, addr, 4);
}
/**
*@brief		This function is to set the MR register.
*@param		val: the value to set to MR  
*@return	None
*/
void setMR(uint8_t val)
{
	IINCHIP_WRITE(MR, val);
}

/**
*@brief		This function is to get Interrupt register in common register.
*@param		None  
*@return	The value read from the IR register
*/
uint8_t getIR(void)
{
	return IINCHIP_READ(IR);
}

/**
@brief		This function is to set up Retransmission time.
					If there is no response from the peer or delay in response then retransmission
					will be there as per RTR (Retry Time-value Register)setting
*@param		timeout: The value write to  the RTR0 register 
*@return	None
*/
void setRTR(uint16_t timeout)
{
//  IINCHIP_WRITE(RTR0,(uint8_t)((timeout & 0xff00) >> 8));
//  IINCHIP_WRITE(RTR1,(uint8_t)(timeout & 0x00ff));
	W5500_WriteWord(RTR0, timeout);
}

/**
@brief		This function is to set the number of Retransmission.
					If there is no response from the peer or delay in response then recorded time
					as per RTR & RCR register seeting then time out will occur.
*@param		retry: Times to  retry 
*@return	None
*/
void setRCR(uint8_t retry)
{
	IINCHIP_WRITE(WIZ_RCR, retry);
}

/**
*@brief		This function is to the interrupt mask Enable/Disable appropriate Interrupt. ('1' : interrupt enable)
					If any bit in IMR is set as '0' then there is not interrupt signal though the bit is
					set in IR register.
*@param		mask: the bits to clear
*@return	None
*/
void clearIR(uint8_t mask)
{
	IINCHIP_WRITE(IR, ~mask | getIR()); 
}

/**
*@brief  	This function is to set the maximum segment size of TCP in Active Mode), while in Passive Mode this is set by peer
*@param		s: socket number
*@param		Sn_MSSR: the maximum segment size
*@return	None
*/
void setSn_MSS(uint8_t s, uint16_t Sn_MSSR)
{
//	IINCHIP_WRITE(Sn_MSSR0(s), (uint8_t)((Sn_MSSR & 0xff00) >> 8));
//	IINCHIP_WRITE(Sn_MSSR1(s), (uint8_t)(Sn_MSSR & 0x00ff));
	W5500_WriteWord(Sn_MSSR0(s), Sn_MSSR);
}
/**
*@brief  	This function is to set the IP Time to live(TTL) Register
*@param		s: socket number
*@param		Sn_MSSR: the IP Time to live
*@return	None
*/
void setSn_TTL(uint8_t s, uint8_t ttl)
{    
	IINCHIP_WRITE(Sn_TTL(s), ttl);
}

/**
*@brief		This function is to read the Interrupt & Soket Status registe
*@param		s: socket number
*@return	socket interrupt status
*/
uint8_t getSn_IR(uint8_t s)
{
	return IINCHIP_READ(Sn_IR(s));
}

/**
*@brief 	This function is to write the Interrupt & Soket Status register to clear the interrupt
*@param		s: socket number
*@return  socket interrupt status
*/
void setSn_IR(uint8_t s, uint8_t val)
{
	IINCHIP_WRITE(Sn_IR(s), val);
}

/**
*@brief 	This function is to get socket status
*@param		s: socket number
*@return  socket status
*/
uint8_t getSn_SR(uint8_t s)
{
	return IINCHIP_READ(Sn_SR(s));
}

/**
*@brief		This fuction is to get socket TX free buf size
					This gives free buffer size of transmit buffer. This is the data size that user can transmit.
					User shuold check this value first and control the size of transmitting data
*@param		s: socket number
*@return  socket TX free buf size
*/
uint16_t getSn_TX_FSR(uint8_t s)
{
	uint16_t val = 0, val1 = 0;
	do
	{
		//    val1 = IINCHIP_READ(Sn_TX_FSR0(s));
		//    val1 = (val1 << 8) + IINCHIP_READ(Sn_TX_FSR1(s));
		val1 = W5500_ReadWord(Sn_TX_FSR0(s));
		if (val1 != 0)
		{
			//			val = IINCHIP_READ(Sn_TX_FSR0(s));
			//			val = (val << 8) + IINCHIP_READ(Sn_TX_FSR1(s));
			val = W5500_ReadWord(Sn_TX_FSR0(s));
		}
	} while (val != val1);
	return val;
}

/**
*@brief		This fuction is to give size of received data in receive buffer.
*@param		s: socket number
*@return  socket TX free buf size
*/
uint16_t getSn_RX_RSR(uint8_t s)
{
	uint16_t val=0,val1=0;
	do
	{
//    val1 = IINCHIP_READ(Sn_RX_RSR0(s));
//    val1 = (val1 << 8) + IINCHIP_READ(Sn_RX_RSR1(s));
		val1 = W5500_ReadWord(Sn_RX_RSR0(s));
		if(val1 != 0)
		{
//        val = IINCHIP_READ(Sn_RX_RSR0(s));
//        val = (val << 8) + IINCHIP_READ(Sn_RX_RSR1(s));
			val = W5500_ReadWord(Sn_RX_RSR0(s));
		}
	} while (val != val1);
	return val;
}

/**
*@brief   This function is being called by send() and sendto() function also.

					This function read the Tx write pointer register and after copy the data in buffer update the Tx write pointer
					register. User should read upper byte first and lower byte later to get proper value.
*@param		s: socket number
*@param		data: data buffer to send
*@param		len: data length
*@return  socket TX free buf size
*/
void send_data_processing(uint8_t s, uint8_t *data, uint16_t len)
{
	uint16_t ptr =0;
	uint32_t addrbsb =0;
#ifdef __DEF_IINCHIP_DBG__
	if(len == 0)
	{
		printf("CH: %d Unexpected1 length 0\r\n", s);
		return;
	}
#endif  
//  ptr = IINCHIP_READ( Sn_TX_WR0(s) );
//  ptr = ((ptr & 0x00ff) << 8) + IINCHIP_READ(Sn_TX_WR1(s));
	ptr = W5500_ReadWord(Sn_TX_WR0(s));

	addrbsb = (uint32_t)(ptr<<8) + (s<<5) + 0x10;	//0x10--Socket 0发送缓冲区偏移地址
	wiz_write_buf(addrbsb, data, len);
  
	ptr += len;
//  IINCHIP_WRITE( Sn_TX_WR0(s) ,(uint8_t)((ptr & 0xff00) >> 8));
//  IINCHIP_WRITE( Sn_TX_WR1(s),(uint8_t)(ptr & 0x00ff));
	W5500_WriteWord(Sn_TX_WR0(s), ptr);
}

/**
*@brief  	This function is being called by recv() also.
					This function read the Rx read pointer register
					and after copy the data from receive buffer update the Rx write pointer register.
					User should read upper byte first and lower byte later to get proper value.
*@param		s: socket number
*@param		data: data buffer to receive
*@param		len: data length
*@return  None
*/
void recv_data_processing(uint8_t s, uint8_t *data, uint16_t len)
{
	uint16_t ptr = 0;
	uint32_t addrbsb = 0;
  
#ifdef __DEF_IINCHIP_DBG__
	if(len == 0)
	{
		printf("CH: %d Unexpected2 length 0\r\n", s);
		return;
	}
#endif
//  ptr = IINCHIP_READ( Sn_RX_RD0(s) );
//  ptr = ((ptr & 0x00ff) << 8) + IINCHIP_READ( Sn_RX_RD1(s) );
	ptr = W5500_ReadWord(Sn_RX_RD0(s));

	addrbsb = (uint32_t)(ptr<<8) + (s<<5) + 0x18;	//0x18--Socket 0接收缓冲区偏移地址
	wiz_read_buf(addrbsb, data, len);
	ptr += len;

//  IINCHIP_WRITE( Sn_RX_RD0(s), (uint8_t)((ptr & 0xff00) >> 8));
//  IINCHIP_WRITE( Sn_RX_RD1(s), (uint8_t)(ptr & 0x00ff));
	W5500_WriteWord(Sn_RX_RD0(s), ptr);
}

/**
*@brief		This function set the transmit & receive buffer size as per the channels is used
*@Note: 	TMSR and RMSR bits are as follows\n
					Maximum memory size for Tx, Rx in the W5500 is 16K Bytes,\n
					In the range of 16KBytes, the memory size could be allocated dynamically by each channel.\n
					Be attentive to sum of memory size shouldn't exceed 8Kbytes\n
					and to data transmission and receiption from non-allocated channel may cause some problems.\n
					If the 16KBytes memory is already  assigned to centain channel, \n
					other 3 channels couldn't be used, for there's no available memory.\n
					If two 4KBytes memory are assigned to two each channels, \n
					other 2 channels couldn't be used, for there's no available memory.\n
*@param		tx_size: tx buffer size to set=tx_size[s]*(1024)
*@param		rx_size: rx buffer size to set=rx_size[s]*(1024)
*@return	None
*/
void socket_buf_init(uint8_t * tx_size, uint8_t * rx_size)
{
	int16_t i;
	int16_t ssum=0,rsum=0;
 
	for (i = 0 ; i < MAX_SOCK_NUM; i++)       // Set the size, masking and base address of Tx & Rx memory by each channel
	{
		IINCHIP_WRITE( (Sn_TXMEM_SIZE(i)), tx_size[i]);
		IINCHIP_WRITE( (Sn_RXMEM_SIZE(i)), rx_size[i]);
          
#ifdef DEBUG
        printf("tx_size[%d]: %d, Sn_TXMEM_SIZE = %d\r\n",i, tx_size[i], IINCHIP_READ(Sn_TXMEM_SIZE(i)));
        printf("rx_size[%d]: %d, Sn_RXMEM_SIZE = %d\r\n",i, rx_size[i], IINCHIP_READ(Sn_RXMEM_SIZE(i)));
#endif
		SSIZE[i] = 0;
		RSIZE[i] = 0;
	
		if (ssum <= 16384)
		{
			SSIZE[i] = (int16_t)tx_size[i]*(1024);
		}

		if (rsum <= 16384)
		{
			RSIZE[i]=(int16_t)rx_size[i]*(1024);
		}
		ssum += SSIZE[i];
		rsum += RSIZE[i];
	}
}
#pragma endregion

